﻿#region << 文 件 说 明 >>
/*----------------------------------------------------------------
// 文件名称：ModelEditViewModel
// 创 建 者：杨程
// 创建时间：2021/9/18 15:48:50
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//		
//
//----------------------------------------------------------------*/
#endregion

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using V.CodeGenerator.CreateCodes;
using V.CodeGenerator.Model;
using V.CodeGenerator.ViewModel.Model;
using Vampirewal.Core.Extensions;
using Vampirewal.Core.Interface;
using Vampirewal.Core.SimpleMVVM;
using Vampirewal.Core.Tools;
using Vampirewal.Core.IoC;
using Vampirewal.Core;
using Vampirewal.Core.WpfTheme.WindowStyle;
using Vampirewal.Core.Models;

namespace V.CodeGenerator.ViewModel
{
    [VampirewalIoCRegister(ViewModelKey.ModelEditViewModel, RegisterType.ViewModel)]
    public class ModelEditViewModel:DetailVM<ProjectModelDtl>
    {
        private IDialogMessage Dialog;
        public ModelEditViewModel(IDialogMessage dialog,IDataContext dc)
        {
            //构造函数
            Dialog = dialog;
            DC = dc;
        }

        public override void InitData()
        {
            InheritanceProp = new ObservableCollection<ModelEdit>();
            CustomProp = new ObservableCollection<ModelEdit>();

            EnumValues = EnumHelper.EnumToList<PropType>().Where(e => e.Classification >= 1 && e.Classification <= 5).OrderBy(e => e.Classification).ToList();

            
        }

        public override void MessengerRegister()
        {
            Messenger.Default.Register<ProjectModelDtl>(this, "GetModelEditEntity", GetModelEditEntity);

            Messenger.Default.Register(this, "ClearModelEditEntity", (() => { this.SetEntity(new ProjectModelDtl()); InheritanceProp.Clear(); CustomProp.Clear(); IsSave = true; }));
        }

        #region 属性
        /// <summary>
        /// 判断当前页面是否保存,所展示的所有内容，一旦变动，均将设置为false
        /// </summary>
        public bool IsSave { get; set; } = true;

        /// <summary>
        /// 继承字段展示
        /// </summary>
        public ObservableCollection<ModelEdit> InheritanceProp { get; set; }

        /// <summary>
        /// 自定义的属性字段展示
        /// </summary>
        public ObservableCollection<ModelEdit> CustomProp { get; set; }


        public List<EnumberCreditType> EnumValues { get; set; }

        
        #endregion

        #region 公共方法

        #endregion

        #region 私有方法
        private void GetModelEditEntity(ProjectModelDtl entity)
        {
            if (IsSave)
            {
                SetEntity(entity);
                CustomProp.Clear();
                var current = DC.Client.Queryable<ModelEdit>().Where(w => w.ProjectModelDtlId == entity.DtlId).ToList();
                CustomProp = current.ListToObservableCollection(CustomProp);

                IsSave = !IsSave;
                
                //switch (entity.Inheritance)
                //{
                //    case "BaseModel":
                //        IsBaseModel = true;
                //        IsPersistModel = false;
                //        IsTreeModel = false;
                //        break;
                //    case "PersistModel":
                //        IsBaseModel = false;
                //        IsPersistModel = true;
                //        IsTreeModel = false;
                //        break;
                //    case "TreeModel":
                //        IsBaseModel = false;
                //        IsPersistModel = false;
                //        IsTreeModel = true;
                //        break;
                //}

                SelectInheritanceWayChange(entity.Inheritance);
            }
            else
            {
                Dialog.ShowPopupWindow($"当前 {entity.DtlName} 模型未保存！", (Window)View, MessageType.Error);
            }
        }
        #endregion

        #region 命令
        public RelayCommand SaveEntityCommand => new RelayCommand(() => 
        {
            try
            {
                DC.Client.BeginTran();

                DoUpdate();

                foreach (var item in CustomProp)
                {
                    DC.UpdateEntity(item);
                }

                DC.UpdateEntityList(CustomProp.ToList());

                DC.Client.CommitTran();
                IsSave = true;

                Dialog.ShowPopupWindow("保存成功！", (Window)View, MessageType.Successful);
            }
            catch
            {
                DC.Client.RollbackTran();
                IsSave = false;

                Dialog.ShowPopupWindow("保存失败！", (Window)View, MessageType.Error);
            }
        });


        public RelayCommand<string> TextChangedCommand => new RelayCommand<string>((s) => { IsSave = false; });

        #region 选择继承基类命令
        public RelayCommand<string> SelectInheritanceWayCommand => new RelayCommand<string>(SelectInheritanceWayChange);

        private void SelectInheritanceWayChange(string s)
        {
            InheritanceProp.Clear();
            switch (s)
            {
                case "BaseModel":
                    CreateInheritanceBaseModel();

                    break;
                case "PersistModel":
                    CreateInheritancePersistModel();
                    break;
                case "TreeModel":
                    CreateIneritanceTreeModel();
                    break;
            }

            IsSave = false;
        }

        private bool _IsBaseModel;
        public bool IsBaseModel
        { 
            get=> _IsBaseModel; 
            set 
            {
                _IsBaseModel = value;
                DoNotify();
            } 
        }
        private void CreateInheritanceBaseModel()
        {
            ModelEdit model1 = new ModelEdit()
            {
                PropName = "UpdateTime",
                propType = PropType.datetime,
                PropDes = "更新时间",
                IsRequired = true
            };
            InheritanceProp.Add(model1);

            ModelEdit model2 = new ModelEdit()
            {
                PropName = "UpdateBy",
                propType = PropType.@string,
                PropDes = "更新人",
                IsRequired = true
            };
            InheritanceProp.Add(model2);

            DtlEntity.Inheritance = "BaseModel";

            IsBaseModel = true;

            IsPersistModel = false;
            IsTreeModel = false;
        }

        private bool _IsPersistModel;

        public bool IsPersistModel 
        { 
            get=> _IsPersistModel;
            set 
            {
                _IsPersistModel = value;
                DoNotify();
            } 
        }
        private void CreateInheritancePersistModel()
        {
            ModelEdit model1 = new ModelEdit()
            {
                PropName = "UpdateTime",
                propType = PropType.datetime,
                PropDes = "更新时间",
                IsRequired = true
            };
            InheritanceProp.Add(model1);

            ModelEdit model2 = new ModelEdit()
            {
                PropName = "UpdateBy",
                propType = PropType.@string,
                PropDes = "更新人",
                IsRequired = true
            };
            InheritanceProp.Add(model2);

            ModelEdit model3 = new ModelEdit()
            {
                PropName = "IsValid",
                propType = PropType.@bool,
                PropDes = "是否逻辑删除",
                IsRequired = true
            };
            InheritanceProp.Add(model3);

            DtlEntity.Inheritance = "PersistModel";

            IsBaseModel = false;
            IsPersistModel = true;
            IsTreeModel = false;
        }

        private bool _IsTreeModel;


        public bool IsTreeModel
        { 
            get=> _IsTreeModel;
            set 
            {
                _IsTreeModel = value;
                DoNotify();
            } 
        }
        private void CreateIneritanceTreeModel()
        {
            ModelEdit model1 = new ModelEdit()
            {
                PropName = "Parent",
                propType = PropType.OneToMany,
                PropDes = "一对多关联",
                IsRequired = false
            };
            InheritanceProp.Add(model1);

            ModelEdit model2 = new ModelEdit()
            {
                PropName = "Childs",
                propType = PropType.ChildTable,
                PropDes = "子表",
                IsRequired = false
            };
            InheritanceProp.Add(model2);

            DtlEntity.Inheritance = "TreeModel";

            IsBaseModel = false;
            IsPersistModel = false;
            IsTreeModel = true;
        }
        #endregion

        /// <summary>
        /// 添加自定义字段的命令
        /// </summary>
        public RelayCommand AddCustomPropDtlCommand => new RelayCommand(() => 
        {
            //ModelEdit model1 = new ModelEdit()
            //{
            //    ProjectModelDtlId=Entity.ID
            //};
            //
            
            var current= Messenger.Default.Send<ModelEdit>("OpenDialogWindowGetResultByPassData","AddOrEditModelEditView",null);

            if (IsValidation(current))
            {
                CustomProp.Add(current);

                try
                {
                    DC.Client.BeginTran();

                    DC.AddEntity(current);


                    DC.Client.CommitTran();

                    IsSave = false;
                }
                catch
                {
                    DC.Client.RollbackTran();

                }
            }
        });

        /// <summary>
        /// 判断一下回传的内容
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private bool IsValidation(ModelEdit model)
        {
            if (string.IsNullOrEmpty( model.PropName))
            {
                return false;
            }
            model.ProjectModelDtlId = DtlEntity.DtlId;

            return true;
        }

        public RelayCommand<ModelEdit> DeleteDtlCommand => new RelayCommand<ModelEdit>((d) =>
        {
            if (d!=null)
            {
                try
                {
                    DC.Client.BeginTran();

                    DC.DeleteEntity(d);

                    DC.Client.CommitTran();

                    IsSave = false;
                }
                catch
                {
                    DC.Client.RollbackTran();

                }

                CustomProp.Remove(d);


            }
        });

        public RelayCommand<ModelEdit> EditDtlCommand => new RelayCommand<ModelEdit>((m) => 
        {
            if (m!=null)
            {
                var current=Messenger.Default.Send<ModelEdit>("OpenDialogWindowGetResultByPassData", "AddOrEditModelEditView", m);

                try
                {
                    DC.Client.BeginTran();
                    
                    DC.UpdateEntity(current);

                    DC.Client.CommitTran();

                    IsSave = false;
                }
                catch
                {
                    DC.Client.RollbackTran();

                }
            }
        });


        public RelayCommand OutModel_Test => new RelayCommand(() => 
        {

            //var model = new CreateCodes.Model.ModelPoco()
            //{
            //    ClassName = Entity.DtlName,
            //    DisplayName=Entity.DisplayName,
            //    TableName = $"{Entity.DtlName}s",
            //    InheritanceBaseModel = Entity.Inheritance
            //};
            //var current = new List<CreateCodes.Model.ModelPropPoco>();
            //foreach (var item in CustomProp)
            //{
                
            //    current.Add(new CreateCodes.Model.ModelPropPoco()
            //    {
            //        PropName=item.PropName,
            //        PropDes=item.PropDes,
            //        propType=item.propType.ToString(),
            //        PropLength=item.PropLength,
            //        PropPrecision=item.PropPrecision,
            //        MinValue=item.MinValue,
            //        MaxValue=item.MaxValue,
            //        IsCreateDbProp=item.IsCreateDbProp,
            //        IsRequired=item.IsRequired
            //    });
            //}
            //model.ModelPropPocos = current;

            //CreateCodes.CreateCodes.ModelPocos.Add(model);

            ////CreateCodes.CreateCodes.CreateModelPoco();

            //CreateCodes.CreateCodes.Build();
        });
        #endregion
    }


}
